package com.huiyujiaoyu.powertime.ui.my;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.huiyujiaoyu.base.AppContext;
import com.huiyujiaoyu.base.BaseActivity;
import com.huiyujiaoyu.http.HttpApi;
import com.huiyujiaoyu.http.HttpMethods;
import com.huiyujiaoyu.powertime.R;
import com.huiyujiaoyu.powertime.model.JsonBean;
import com.huiyujiaoyu.powertime.model.SimpleBean;
import com.huiyujiaoyu.powertime.model.UserInfoBean;
import com.huiyujiaoyu.util.ActivityUtil;
import com.huiyujiaoyu.util.Constant;
import com.huiyujiaoyu.util.DialogUtil;
import com.huiyujiaoyu.util.GlideUtil;
import com.huiyujiaoyu.util.PicCameraLocalUtil;
import com.huiyujiaoyu.util.PopupWindowUtil;
import com.huiyujiaoyu.util.ResourceUtil;
import com.huiyujiaoyu.util.StringUtils;
import com.huiyujiaoyu.util.ToastUtil;
import com.huiyujiaoyu.widget.LlkjToolBar;

import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static com.huiyujiaoyu.util.Constant.RX_CA_WRI;
import static com.huiyujiaoyu.util.PicCameraLocalUtil.revitionImageSize;
import static com.huiyujiaoyu.util.StringUtils.getJson;


/**
 * Created by win7 on 2017/6/18.
 * 个人资料显示界面
 */

public class PersnonalInfoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.toolbar)
    LlkjToolBar mToolbar;
    @BindView(R.id.cir_icon)
    ImageView mCirIcon;
    @BindView(R.id.iv_1)
    ImageView mIv1;
    @BindView(R.id.tv_nicheng)
    TextView mTvNicheng;
    @BindView(R.id.rl_nicheng)
    RelativeLayout mRlNicheng;
    @BindView(R.id.iv_2)
    ImageView mIv2;
    @BindView(R.id.tv_desc)
    TextView mTvDesc;
    @BindView(R.id.rl_desc)
    RelativeLayout mRlDesc;
    @BindView(R.id.iv_3)
    ImageView mIv3;
    @BindView(R.id.tv_shoujihao)
    TextView mTvShoujihao;
    @BindView(R.id.rl_shoujihao)
    RelativeLayout mRlShoujihao;
    @BindView(R.id.iv_4)
    ImageView mIv4;
    @BindView(R.id.tv_dizhi)
    TextView mTvDizhi;
    @BindView(R.id.rl_dizhi)
    RelativeLayout mRlDizhi;
    @BindView(R.id.btn_save)
    Button mBtnSave;
    private File cameraFile;// 拍照文件
    private PopupWindow pw;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;
    private int fromType = 1;
    private OptionsPickerView opv2;
    private Map<String,Object> params;
    private String headerpath;
    public static void launch(Context context) {
        ActivityUtil.startActivity(context, PersnonalInfoActivity.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_info;

    }

    @Override
    protected void onResume() {
        super.onResume();
        mTvNicheng.setText(UserInfoBean.getInstance().getNickName());
        mTvDesc.setText(UserInfoBean.getInstance().getSignature());
        mTvShoujihao.setText(UserInfoBean.getInstance().getPhone());
        mTvDizhi.setText(UserInfoBean.getInstance().getAddress());
        GlideUtil.loadHeaderImg(mCirIcon, StringUtils.getFullUrl(UserInfoBean.getInstance().getHeadImg()));
    }

    @Override
    protected void initView() {
        super.initView();
        setToolbar(mToolbar);
        mToolbar.setToolBar("个人资料", true, "", R.mipmap.icon_titlebar_back, false, "", LlkjToolBar.isNull);
        pw = PopupWindowUtil.getPopupWindowFromBottom(this, new PopupWindowUtil.PhotoDoWhat() {
            @Override
            public void doone() {
                fromType = 1;
                checkPer();
            }

            @Override
            public void dotwo() {
                fromType = 0;
                checkPer();

            }
        }, "拍照", "相册");
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        params = new HashMap<>();
    }

    public void getPic() {
        if (fromType == 0) {
            PicCameraLocalUtil.selectPicFromLocal(PersnonalInfoActivity.this);
        } else if (fromType == 1) {
            cameraFile = PicCameraLocalUtil.selectPicFromCamera(PersnonalInfoActivity.this, cameraFile);
        }
    }

    private void checkPer() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
            getPic();
        } else {
            EasyPermissions.requestPermissions(this, "拍照需要摄像头权限",
                    RX_CA_WRI, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //成功
        getPic();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ToastUtil.makeShortText(mContext, "你拒绝了相应的权限");

    }

    @OnClick({R.id.cir_icon, R.id.rl_nicheng, R.id.rl_desc, R.id.rl_shoujihao, R.id.rl_dizhi,R.id.btn_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cir_icon:
                PopupWindowUtil.showBottom(this, pw, view);
                break;
            case R.id.rl_nicheng:
                UpdateNiceNameActivity.launch(mContext);
                break;
            case R.id.rl_desc:
                 UpdataDescActivity.launch(mContext);
                break;
            case R.id.rl_shoujihao:
                 UpdataPhoneVerifActivity.launch(mContext);
                break;
            case R.id.rl_dizhi:
                if (isLoaded) {
                    if (opv2 == null) {
                        opv2 = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                //返回的分别是三个级别的选中位置
                                String data1 = options1Items.get(options1).getPickerViewText();
                                String data2 = options2Items.get(options1).get(options2);
                                params.put("province",data1);
                                params.put("city",data2);
                                mTvDizhi.setText(data1+""+data2);
                            }
                        })
                                .setTitleText("城市选择")
                                .setTitleColor(ResourceUtil.getColor(AppContext.context(), R.color.title_bg))//标题文字颜色
                                .setSubmitColor(ResourceUtil.getColor(AppContext.context(), R.color.gray))//确定按钮文字颜色
                                .setCancelColor(ResourceUtil.getColor(AppContext.context(), R.color.gray))//取消按钮文字颜色
                                .setTitleBgColor(ResourceUtil.getColor(AppContext.context(), android.R.color.white))//标题背景颜色 Night mode
                                .setBgColor(ResourceUtil.getColor(AppContext.context(), android.R.color.white))//滚轮背景颜色 Night mode
                                .setContentTextSize(20)
                                .setOutSideCancelable(false)// default is true
                                .build();
                        opv2.setPicker(options1Items, options2Items);//二级选择器*/
                    }
                    DialogUtil.showDialog(opv2);
                } else {
                    Toast.makeText(this, "数据暂未解析成功，请等待", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_save:
                HttpMethods.getInstance().update(mContext,getComp(),this,params);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case Constant.REQUEST_CODE_LOCAL:// 直接从相册获取
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        String picturePath = PicCameraLocalUtil.getPicByUri(
                                this, selectedImage);
                        try {
                            headerpath =  revitionImageSize(
                                    picturePath, this).getAbsolutePath();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(!TextUtils.isEmpty(headerpath)){
                            uploadImag();
                        }else{
                            ToastUtil.makeShortText(mContext,"文件为空");
                        }
                    }
                }
                PopupWindowUtil.dissPw(pw);
                break;
            case Constant.REQUEST_CODE_CAMERA:// 调用相机拍照
                if (cameraFile != null && cameraFile.exists()) {
                    //上传图片
                    try {
                        headerpath =   PicCameraLocalUtil.revitionImageSize(cameraFile.getAbsolutePath(), this).getAbsolutePath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(!TextUtils.isEmpty(headerpath)){
                        uploadImag();
                    }else{
                        ToastUtil.makeShortText(mContext,"文件为空");
                    }
                }
                PopupWindowUtil.dissPw(pw);
                break;
        }
    }

    public void uploadImag(){
        HttpMethods.getInstance().uploadimg(mContext,getComp(),this,1,headerpath);
    }

    @Override
    public void onNext(Object o, int httpcode) {
        super.onNext(o, httpcode);
        switch (httpcode) {
            case HttpApi.HTTP_UPLOADIMG:
                UserInfoBean.getInstance().setHeadImg(((SimpleBean) o).url);
                GlideUtil.loadHeaderImg(mCirIcon, StringUtils.getFullUrl(UserInfoBean.getInstance().getHeadImg()));
                break;
            case HttpApi.HTTP_UPDATE:
                UserInfoBean.getInstance().setAddress(mTvDizhi.getText()+"");
                break;
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        // Toast.makeText(MyFileActivity.this,"开始解析数据",Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    // Toast.makeText(MyFileActivity.this,"解析数据成功",Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    // Toast.makeText(MyFileActivity.this,"解析数据失败",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            //options3Items.add(Province_AreaList);
        }
        //完成
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
